<!DOCTYPE html>


<html lang="en">
  

    <head>
      <meta charset="utf-8" />
        
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>入门-Golang之路 |  朝花夕拾</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/ww.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      
<link rel="stylesheet" href="/css/fonts/remixicon.css">

      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.staticfile.org/pace/1.2.4/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    </head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-入门-Golang之路"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  入门-Golang之路
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2023/05/10/%E5%85%A5%E9%97%A8-Golang%E4%B9%8B%E8%B7%AF/" class="article-date">
  <time datetime="2023-05-10T00:59:14.000Z" itemprop="datePublished">2023-05-10</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Golang/">Golang</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">4.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">26 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="Golang之路"><a href="#Golang之路" class="headerlink" title="Golang之路"></a>Golang之路</h1><p>g</p>
<h2 id="下载"><a href="#下载" class="headerlink" title="下载"></a>下载</h2><p>​	<a target="_blank" rel="noopener" href="https://golang.google.cn/">https://golang.google.cn/</a></p>
<p>​	<a target="_blank" rel="noopener" href="https://golang.google.cn/dl/">https://golang.google.cn/dl/</a></p>
<p>​	版本： go.1.18</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><ol>
<li>GOROOT&#x3D;D:\go1.18</li>
<li>GOPATH&#x3D;D:\gopath1.18</li>
<li>GO111MODULE&#x3D;on</li>
<li>GOPROXY&#x3D;<a target="_blank" rel="noopener" href="https://goproxy.cn,direct/">https://goproxy.cn,direct</a></li>
</ol>
<h2 id="go-mod-创建项目"><a href="#go-mod-创建项目" class="headerlink" title="go mod 创建项目"></a>go mod 创建项目</h2><ol>
<li>新建目录： D:\gopath1.18\cdr</li>
<li>进入该目录下： …</li>
<li>初始化项目：   go mod init cdr</li>
<li>下载包：   go get github.com&#x2F;gin-gonic&#x2F;gin   （下载完在这里：D:\gopath1.18\pkg\mod）</li>
<li>刷新包：  go mod tidy</li>
<li>Goland打开项目，import后根据红线提示编目index，再开始丝滑</li>
</ol>
<h2 id="gin"><a href="#gin" class="headerlink" title="gin"></a>gin</h2><p>在线文档： <a target="_blank" rel="noopener" href="https://www.itying.com/gin">https://www.itying.com/gin</a></p>
<p>我的专栏： <a target="_blank" rel="noopener" href="https://www.itying.com/category-79-b0.html">https://www.itying.com/category-79-b0.html</a></p>
<p>官网： <a target="_blank" rel="noopener" href="https://gin-gonic.com/zh-cn">https://gin-gonic.com/zh-cn</a></p>
<h3 id="gin基本结构"><a href="#gin基本结构" class="headerlink" title="gin基本结构"></a>gin基本结构</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">		r := gin.Default()</span><br><span class="line">​		r.LoadHTMLGlob(<span class="string">&quot;templates/*&quot;</span>)</span><br><span class="line">​		r.GET(<span class="string">&quot;/&quot;</span>,funcName)</span><br><span class="line"><span class="number">1.</span>GET 	 查</span><br><span class="line"><span class="number">2.</span>POST   增</span><br><span class="line"><span class="number">3.</span>PUT    改</span><br><span class="line"><span class="number">4.</span>DELETE 删</span><br><span class="line">​		funcName(c *gin.Context)&#123;	</span><br><span class="line">​			c.<span class="type">string</span>(<span class="number">200</span>,<span class="string">&quot;aaaaaaaaaaa&quot;</span>)</span><br><span class="line">​		&#125;</span><br><span class="line"><span class="number">1.</span> c.<span class="type">string</span> 返回字符串</span><br><span class="line"><span class="number">2.</span> c.json   返回json</span><br><span class="line"><span class="number">3.</span> c.jsonp  返回jsonp</span><br><span class="line"><span class="number">4.</span> c.xml    返回xml</span><br><span class="line"><span class="number">5.</span> c.html   返回网页,需要先加载模板：r.LoadHTMLGlob(<span class="string">&quot;templates/*&quot;</span>) &#123;&#123;.变量名称&#125;&#125;</span><br><span class="line">​		r.Run(<span class="string">&quot;:8080&quot;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="gin模板放在不同目录里面的配置方法"><a href="#gin模板放在不同目录里面的配置方法" class="headerlink" title="gin模板放在不同目录里面的配置方法"></a>gin模板放在不同目录里面的配置方法</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//引擎</span></span><br><span class="line">r.LoadHTMLGlob(<span class="string">&quot;templates/**/*&quot;</span>)</span><br><span class="line"><span class="comment">//模板起名</span></span><br><span class="line">&#123;&#123; define <span class="string">&quot;aaa/a111.html&quot;</span> &#125;&#125;</span><br><span class="line">&#123;&#123; end &#125;&#125;</span><br><span class="line"><span class="comment">//路由方法使用模板</span></span><br><span class="line">c.html(<span class="number">200</span>,<span class="string">&quot;aaa/a111.html&quot;</span>,<span class="keyword">map</span>[<span class="type">string</span>]&#123;&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="gin模板嵌套"><a href="#gin模板嵌套" class="headerlink" title="gin模板嵌套"></a>gin模板嵌套</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; template <span class="string">&quot;aaa/a111.html&quot;</span> . &#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="gin前端变量"><a href="#gin前端变量" class="headerlink" title="gin前端变量"></a>gin前端变量</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; $a := .name &#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="gin前端移除空格"><a href="#gin前端移除空格" class="headerlink" title="gin前端移除空格"></a>gin前端移除空格</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;- .name -&#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="gin前端比较函数"><a href="#gin前端比较函数" class="headerlink" title="gin前端比较函数"></a>gin前端比较函数</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eq lt gt le ge ne</span><br></pre></td></tr></table></figure>

<h3 id="gin前端条件判断"><a href="#gin前端条件判断" class="headerlink" title="gin前端条件判断"></a>gin前端条件判断</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; <span class="keyword">if</span> gt .score <span class="number">80</span> &#125;&#125;</span><br><span class="line">	优秀</span><br><span class="line">&#123;&#123; <span class="keyword">else</span> <span class="keyword">if</span> gt $score <span class="number">60</span> &#125;&#125;</span><br><span class="line">	及格</span><br><span class="line">&#123;&#123; <span class="keyword">else</span> &#125;&#125;</span><br><span class="line">	不及格</span><br><span class="line">&#123;&#123; end &#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="gin前端range循环"><a href="#gin前端range循环" class="headerlink" title="gin前端range循环"></a>gin前端range循环</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;dl&gt;</span><br><span class="line">	&#123;&#123; <span class="keyword">range</span> $i,$v := .obj &#125;&#125;</span><br><span class="line">		&lt;li&gt; &#123;&#123; key为$i，值为$v &#125;&#125;  &lt;/li&gt;</span><br><span class="line">	&#123;&#123; <span class="keyword">else</span> &#125;&#125;</span><br><span class="line">		a数组为空</span><br><span class="line">	&#123;&#123; end &#125;&#125;</span><br><span class="line">&lt;/dl&gt;</span><br></pre></td></tr></table></figure>

<h3 id="gin前端with解构"><a href="#gin前端with解构" class="headerlink" title="gin前端with解构"></a>gin前端with解构</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; with .atype &#125;&#125;</span><br><span class="line"><span class="comment">//然后a结构体就被赋值给.了</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin前端预定义函数"><a href="#gin前端预定义函数" class="headerlink" title="gin前端预定义函数"></a>gin前端预定义函数</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">and , or , not , <span class="built_in">len</span> , index</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin自定义函数"><a href="#gin自定义函数" class="headerlink" title="gin自定义函数"></a>gin自定义函数</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">r.SetFuncMap(template.FuncMap&#123;</span><br><span class="line">    <span class="string">&quot;formatDate&quot;</span>:formatAsDate,   </span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin静态文件服务"><a href="#gin静态文件服务" class="headerlink" title="gin静态文件服务"></a>gin静态文件服务</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    r := gin.Default()</span><br><span class="line">    r.Static(<span class="string">&quot;/static&quot;</span>,<span class="string">&quot;./static&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//把程序本目录下的s目录映给s路由</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="get传值给go"><a href="#get传值给go" class="headerlink" title="get传值给go"></a>get传值给go</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">r.GET(<span class="string">&quot;/getValue&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    username := c.Query(<span class="string">&quot;username&quot;</span>)</span><br><span class="line">    age := c.Query(<span class="string">&quot;age&quot;</span>)</span><br><span class="line">    page := c.DefaultQuery(<span class="string">&quot;page&quot;</span>,<span class="string">&quot;2&quot;</span>)</span><br><span class="line">    c.JSON(<span class="number">200</span>,gin.H&#123;</span><br><span class="line">        <span class="string">&quot;username&quot;</span> : username,</span><br><span class="line">        <span class="string">&quot;age&quot;</span> : age,</span><br><span class="line">        <span class="string">&quot;page&quot;</span> : page,</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//测试： http://1.1.1.1:8080/getValue?username=%E6%B1%AA%E4%BC%9F&amp;age=99</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="post传值给go"><a href="#post传值给go" class="headerlink" title="post传值给go"></a>post传值给go</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//去到表单页</span></span><br><span class="line">r.GET(<span class="string">&quot;/addUser&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    c.HTML(<span class="number">200</span>,<span class="string">&quot;default/addUser.html&quot;</span>,<span class="keyword">map</span>[<span class="type">string</span>]<span class="keyword">interface</span>&#123;&#125;&#123;&#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 表单提交给路由 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/doAddUser&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span>&gt;</span></span><br><span class="line">    用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> /&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    密 码：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> /&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;提交&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//执行路由post方法,golang获取表单值</span></span><br><span class="line">r.POST(<span class="string">&quot;/doAddUser&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">	username := c.PostForm(<span class="string">&quot;username&quot;</span>)</span><br><span class="line">	password := c.PostForm(<span class="string">&quot;password&quot;</span>)</span><br><span class="line">	age := c.DefaultPostForm(<span class="string">&quot;age&quot;</span>, <span class="string">&quot;26&quot;</span>)</span><br><span class="line">	c.JSON(<span class="number">200</span>, gin.H&#123;</span><br><span class="line">		<span class="string">&quot;username&quot;</span>: username,</span><br><span class="line">		<span class="string">&quot;password&quot;</span>: password,</span><br><span class="line">		<span class="string">&quot;age&quot;</span>:      age,</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="get传值绑定到结构体"><a href="#get传值绑定到结构体" class="headerlink" title="get传值绑定到结构体"></a>get传值绑定到结构体</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> UserInfo <span class="keyword">struct</span>&#123;</span><br><span class="line">    Username <span class="type">string</span> <span class="string">`json:&quot;username&quot; form:&quot;username&quot;`</span></span><br><span class="line">    Password <span class="type">string</span> <span class="string">`json:&quot;password&quot; form:&quot;password&quot;`</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">r.GET(<span class="string">&quot;/getUser&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    user := &amp;UserInfo&#123;&#125;</span><br><span class="line">    <span class="keyword">if</span> err := c.ShouldBind(&amp;user); err == <span class="literal">nil</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">200</span>,user)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">200</span>,gin.H&#123;</span><br><span class="line">            <span class="string">&quot;ERR&quot;</span> : err.Error(),</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 测试 ： http://1.1.1.1:8080/getUser?username=%E6%B1%AA%E4%BC%9F&amp;password=0998*aa</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="post传值绑定到结构体"><a href="#post传值绑定到结构体" class="headerlink" title="post传值绑定到结构体"></a>post传值绑定到结构体</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//去到表单页</span></span><br><span class="line">r.GET(<span class="string">&quot;/addUser&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    c.HTML(<span class="number">200</span>,<span class="string">&quot;default/addUser.html&quot;</span>,<span class="keyword">map</span>[<span class="type">string</span>]<span class="keyword">interface</span>&#123;&#125;&#123;&#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 表单提交给路由 --&gt;</span><br><span class="line">&lt;form action=&quot;/doAddUser2&quot; method=&quot;post&quot;&gt;</span><br><span class="line">    用户名：&lt;input type=&quot;text&quot; name=&quot;username&quot; /&gt; &lt;br&gt;&lt;br&gt;</span><br><span class="line">    密 码：&lt;input type=&quot;password&quot; name=&quot;password&quot; /&gt; &lt;br&gt;&lt;br&gt;</span><br><span class="line">    &lt;input type=&quot;submit&quot; value=&quot;提交&quot;&gt;</span><br><span class="line">&lt;/form&gt;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">r.POST(<span class="string">&quot;/doAddUser2&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    user := &amp;UserInfo&#123;&#125;</span><br><span class="line">    <span class="keyword">if</span> err := c.ShouldBind(&amp;user); err == <span class="literal">nil</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">200</span>,user)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">400</span>,gin.H&#123;</span><br><span class="line">            <span class="string">&quot;ERR&quot;</span> : err.Error(),</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="xml数据绑定到结构体"><a href="#xml数据绑定到结构体" class="headerlink" title="xml数据绑定到结构体"></a>xml数据绑定到结构体</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">article</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">content</span> <span class="attr">type</span>=<span class="string">&quot;string&quot;</span>&gt;</span>我是张三<span class="tag">&lt;/<span class="name">content</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span> <span class="attr">type</span>=<span class="string">&quot;string&quot;</span>&gt;</span>张三<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">article</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Article <span class="keyword">struct</span>&#123;</span><br><span class="line">    Title <span class="type">string</span> <span class="string">`json:&quot;title&quot; xml:&quot;title&quot;`</span></span><br><span class="line">    Content <span class="type">string</span> <span class="string">`json:&quot;content&quot; xml:&quot;content&quot;`</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">r.POST(<span class="string">&quot;/xml&quot;</span>,<span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span>&#123;</span><br><span class="line">    article := &amp;Article&#123;&#125;</span><br><span class="line">    xmlSliceDate,_ = c.GetRawDate() <span class="comment">//获取c.Request.Body字节流</span></span><br><span class="line">    <span class="keyword">if</span> err := xml.Unmarshal(xmlSliceDate,&amp;article); err == <span class="literal">nil</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">200</span>,article)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        c.JSON(<span class="number">400</span>,gin.H&#123;</span><br><span class="line">            <span class="string">&quot;ERR&quot;</span> : err.Error(),</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin动态路由"><a href="#gin动态路由" class="headerlink" title="gin动态路由"></a>gin动态路由</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">r.GET(&quot;/list/:cid&quot;, func(c *gin.Context)&#123;</span><br><span class="line">	cid := c.Param(&quot;cid&quot;)</span><br><span class="line">	c.String(200,&quot;%v&quot;,cid)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin加载css文件和jsp文件"><a href="#gin加载css文件和jsp文件" class="headerlink" title="gin加载css文件和jsp文件"></a>gin加载css文件和jsp文件</h3><p>参考网站： <a target="_blank" rel="noopener" href="https://blog.51cto.com/dongweizhen/3606790">https://blog.51cto.com/dongweizhen/3606790</a></p>
<p>新增目录结构：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">templates/statics/index.css</span><br><span class="line">templates/statics/index.js</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>main.go内容</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">&quot;github.com/gin-gonic/gin&quot;</span></span><br><span class="line">	<span class="string">&quot;html/template&quot;</span></span><br><span class="line">	<span class="string">&quot;net/http&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">//定义一个路由</span></span><br><span class="line">	r := gin.Default()</span><br><span class="line">	<span class="comment">//加载静态文件</span></span><br><span class="line">	r.Static(<span class="string">&quot;/dwz&quot;</span>,<span class="string">&quot;templates/statics&quot;</span>)</span><br><span class="line">	<span class="comment">//添加自定义函数，解析下面的“百度一下”html代码</span></span><br><span class="line">	r.SetFuncMap(template.FuncMap&#123;</span><br><span class="line">		<span class="string">&quot;safe&quot;</span>: <span class="function"><span class="keyword">func</span><span class="params">(str <span class="type">string</span>)</span></span> template.HTML&#123;</span><br><span class="line">			<span class="keyword">return</span> template.HTML(str)</span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;)</span><br><span class="line">	<span class="comment">//模板解析</span></span><br><span class="line">	r.LoadHTMLGlob(<span class="string">&quot;templates/**/*&quot;</span>)</span><br><span class="line">	<span class="comment">//模板渲染</span></span><br><span class="line">	r.GET(<span class="string">&quot;/posts&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">		c.HTML(http.StatusOK, <span class="string">&quot;posts/index.tmpl&quot;</span>, gin.H&#123;</span><br><span class="line">			<span class="string">&quot;title&quot;</span>: <span class="string">&quot;Posts index&quot;</span>,</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;)</span><br><span class="line">	r.GET(<span class="string">&quot;/users&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">		c.HTML(http.StatusOK, <span class="string">&quot;users/index.tmpl&quot;</span>, gin.H&#123;</span><br><span class="line">			<span class="string">&quot;title&quot;</span>: <span class="string">&quot;&lt;a href=&#x27;https://www.baidu.com&#x27;&gt;百度一下&lt;/a&gt;&quot;</span>,</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;)</span><br><span class="line">	r.Run(<span class="string">&quot;:9090&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>templates&#x2F;statics&#x2F;index.css内容</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">body &#123;</span><br><span class="line">    background-color: cadetblue;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>templates&#x2F;statics&#x2F;index.js内容</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="number">123</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>templates&#x2F;users&#x2F;index.tmpl内容</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;define <span class="string">&quot;users/index.tmpl&quot;</span>&#125;&#125;</span><br><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">&quot;en&quot;</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">&quot;UTF-8&quot;</span>&gt;</span><br><span class="line">    &lt;link rel=<span class="string">&quot;stylesheet&quot;</span> href=<span class="string">&quot;/dwz/index.css&quot;</span>&gt;</span><br><span class="line">    &lt;title&gt;Title&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&#123;&#123;.title | safe&#125;&#125;</span><br><span class="line">&lt;script src=<span class="string">&quot;/dwz/index.js&quot;</span>&gt;&lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br><span class="line">&#123;&#123;end&#125;&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>运行程序：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">go</span> run main.<span class="keyword">go</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>浏览器访问：</p>
<p>登录后复制  </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//ip:9090/users</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin上传单文件"><a href="#gin上传单文件" class="headerlink" title="gin上传单文件"></a>gin上传单文件</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h2</span>&gt;</span>演示文件上传<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/upload&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span> <span class="attr">enctype</span>=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span></span><br><span class="line">        用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">placeholder</span>=<span class="string">&quot;用户名&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">        头像：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;file&quot;</span> <span class="attr">name</span>=<span class="string">&quot;face&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;提交&quot;</span> /&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">&quot;fmt&quot;</span></span><br><span class="line">	<span class="string">&quot;log&quot;</span></span><br><span class="line"></span><br><span class="line">	<span class="string">&quot;github.com/gin-gonic/gin&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	r := gin.Default()</span><br><span class="line">	r.LoadHTMLGlob(<span class="string">&quot;templates/*&quot;</span>)</span><br><span class="line"></span><br><span class="line">	<span class="comment">//上传操作页</span></span><br><span class="line">	<span class="comment">//设置内存限制（默认是32M），这里设置为8M</span></span><br><span class="line">	r.MaxMultipartMemory = <span class="number">8</span> &lt;&lt; <span class="number">20</span> <span class="comment">//8M</span></span><br><span class="line">	fmt.Println(r.MaxMultipartMemory)</span><br><span class="line">	r.POST(<span class="string">&quot;/upload&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">		file, err := c.FormFile(<span class="string">&quot;face&quot;</span>)</span><br><span class="line">		<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">			fmt.Println(<span class="string">&quot;读取表单失败&quot;</span>)</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">		log.Println(file.Filename)</span><br><span class="line">		path := <span class="string">`D:\go_ftp_dir`</span></span><br><span class="line">		pathFile := path + <span class="string">&quot;/&quot;</span> + file.Filename</span><br><span class="line">		c.SaveUploadedFile(file, pathFile)</span><br><span class="line">		c.String(<span class="number">200</span>, fmt.Sprintf(<span class="string">&quot;&#x27;%s&#x27; uploaded!&quot;</span>, file.Filename))</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br><span class="line">	<span class="comment">//上传接口页</span></span><br><span class="line">	r.GET(<span class="string">&quot;/upload&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(ctx *gin.Context)</span></span> &#123;</span><br><span class="line">		ctx.HTML(<span class="number">200</span>, <span class="string">&quot;upload.html&quot;</span>, gin.H&#123;&#125;)</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br><span class="line">	r.Run(<span class="string">&quot;:8080&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="crul-命令-也可以发送POST请求"><a href="#crul-命令-也可以发送POST请求" class="headerlink" title="crul 命令 也可以发送POST请求"></a>crul 命令 也可以发送POST请求</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">curl -X POST http://localhost:8080/upload \</span><br><span class="line">  -F &quot;file=@/tmp/aaa.zip&quot; \</span><br><span class="line">  -H &quot;Content-Type: multipart/form-data&quot;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="gin上传和下载"><a href="#gin上传和下载" class="headerlink" title="gin上传和下载"></a>gin上传和下载</h3><p>​	批量上传</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">httpRouter.POST(<span class="string">&quot;/upload&quot;</span>, <span class="function"><span class="keyword">func</span><span class="params">(ctx *gin.Context)</span></span> &#123;</span><br><span class="line">		forms, err := ctx.MultipartForm()</span><br><span class="line">		<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">			fmt.Println(<span class="string">&quot;error&quot;</span>, err)</span><br><span class="line">		&#125;</span><br><span class="line">		files := forms.File[<span class="string">&quot;fileName&quot;</span>]</span><br><span class="line">		<span class="keyword">for</span> _, v := <span class="keyword">range</span> files &#123;</span><br><span class="line">			<span class="keyword">if</span> err := ctx.SaveUploadedFile(v, fmt.Sprintf(<span class="string">&quot;%s%s&quot;</span>, <span class="string">&quot;./file/&quot;</span>, v.Filename)); err != <span class="literal">nil</span> &#123;</span><br><span class="line">				fmt.Println(<span class="string">&quot;保存文件失败&quot;</span>)</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>​	其实下载文件，通过http的get请求就行了，回去ctx.file()。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">httpRouter.GET(&quot;/download&quot;, func(ctx *gin.Context) &#123;</span><br><span class="line">		filePath := ctx.Query(&quot;url&quot;)</span><br><span class="line">		//打开文件</span><br><span class="line">		file, err := os.Open(&quot;./&quot; + filePath)</span><br><span class="line">		if err != nil &#123;</span><br><span class="line">			fmt.Println(&quot;打开文件错误&quot;, err)</span><br><span class="line">		&#125;</span><br><span class="line">		defer file.Close()</span><br><span class="line"></span><br><span class="line">		//获取文件的名称</span><br><span class="line">		fileName := path.Base(filePath)</span><br><span class="line">		ctx.Header(&quot;Content-Type&quot;, &quot;application/octet-stream&quot;)</span><br><span class="line">		ctx.Header(&quot;Content-Disposition&quot;, &quot;attachment; url=&quot;+fileName)</span><br><span class="line">		ctx.Header(&quot;Content-Transfer-Encoding&quot;, &quot;binary&quot;)</span><br><span class="line">		ctx.Header(&quot;Cache-Control&quot;, &quot;no-cache&quot;)</span><br><span class="line"></span><br><span class="line">		ctx.File(&quot;./&quot; + filePath)</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<h2 id="自恢复集群启动命令oninitdb的设计与实现-之golang知识点"><a href="#自恢复集群启动命令oninitdb的设计与实现-之golang知识点" class="headerlink" title="自恢复集群启动命令oninitdb的设计与实现 之golang知识点"></a>自恢复集群启动命令oninitdb的设计与实现 之golang知识点</h2><h3 id="go执行os系统命令"><a href="#go执行os系统命令" class="headerlink" title="go执行os系统命令"></a>go执行os系统命令</h3><p>参考网站： <a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/296409942">https://zhuanlan.zhihu.com/p/296409942</a></p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;bytes&quot;</span></span><br><span class="line">    <span class="string">&quot;fmt&quot;</span></span><br><span class="line">    <span class="string">&quot;log&quot;</span></span><br><span class="line">    <span class="string">&quot;os/exec&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    cmd := exec.Command(<span class="string">&quot;ls&quot;</span>, <span class="string">&quot;-l&quot;</span>, <span class="string">&quot;/var/log/*.log&quot;</span>)</span><br><span class="line">    <span class="keyword">var</span> stdout, stderr bytes.Buffer</span><br><span class="line">    cmd.Stdout = &amp;stdout  <span class="comment">// 标准输出</span></span><br><span class="line">    cmd.Stderr = &amp;stderr  <span class="comment">// 标准错误</span></span><br><span class="line">    err := cmd.Run()</span><br><span class="line">    outStr, errStr := stdout.String(), stderr.String()</span><br><span class="line">    fmt.Printf(<span class="string">&quot;out:\n%s\nerr:\n%s\n&quot;</span>, outStr, errStr)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        log.Fatalf(<span class="string">&quot;cmd.Run() failed with %s\n&quot;</span>, err)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="go发送get请求并解析网页的BodyString数据"><a href="#go发送get请求并解析网页的BodyString数据" class="headerlink" title="go发送get请求并解析网页的BodyString数据"></a>go发送get请求并解析网页的BodyString数据</h3><p>参考网站：<a target="_blank" rel="noopener" href="https://cloud.tencent.com/developer/article/1849807">https://cloud.tencent.com/developer/article/1849807</a></p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="comment">//主addrss</span></span><br><span class="line">	fmt.Println(<span class="string">&quot;远程添加&quot;</span>)</span><br><span class="line">	u := <span class="string">&quot;http://&quot;</span> + zhuip + <span class="string">&quot;:&quot;</span> + zhuport + <span class="string">&quot;/addrss?my=&quot;</span> + my</span><br><span class="line">	fmt.Println(u)</span><br><span class="line">	response, err := http.Get(u)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;http.Get addrss 时遇到异常&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	buf, _ := ioutil.ReadAll(response.Body)</span><br><span class="line">	s := <span class="type">string</span>(buf)</span><br><span class="line">	<span class="keyword">if</span> s == <span class="string">&quot;run addrss ok&quot;</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;run addrss ok&quot;</span>)</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;run addrss err&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="go返送get请求并解析网页BodyJSON数据到结构体"><a href="#go返送get请求并解析网页BodyJSON数据到结构体" class="headerlink" title="go返送get请求并解析网页BodyJSON数据到结构体"></a>go返送get请求并解析网页BodyJSON数据到结构体</h3><p>知识点：</p>
<ol>
<li>ioutil.ReadAll(response.Body) 读取所有Body数据</li>
<li>json.Unmarshal(buf, &amp;infoList[i]) 使用一个结构体地址解析json字符串</li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">type Info struct &#123;</span><br><span class="line">	Servername string `JSON:&quot;servername&quot;`</span><br><span class="line">	Mode       string `JSON:&quot;mode&quot;`</span><br><span class="line">	Running    string `JSON:&quot;running&quot;`</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">var infoList [3]Info</span><br><span class="line"></span><br><span class="line">func info() &#123;</span><br><span class="line">	//查看db节点infof</span><br><span class="line">	fmt.Println(&quot;查看集群&quot;)</span><br><span class="line">	for i, n := range webList &#123;</span><br><span class="line">		response, err := http.Get(&quot;http://&quot; + n.ip + &quot;:&quot; + n.port + &quot;/info&quot;)</span><br><span class="line">		if err != nil &#123;</span><br><span class="line">			fmt.Println(&quot;info API 未正常提供服务，Docker可能已经异常。&quot;)</span><br><span class="line">			continue</span><br><span class="line">		&#125;</span><br><span class="line">		buf, _ := ioutil.ReadAll(response.Body)</span><br><span class="line">		json.Unmarshal(buf, &amp;infoList[i])</span><br><span class="line">		fmt.Println(infoList[i])</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h2 id="golang使用sftp和ssh"><a href="#golang使用sftp和ssh" class="headerlink" title="golang使用sftp和ssh"></a>golang使用sftp和ssh</h2><p>参考网站： <a target="_blank" rel="noopener" href="https://www.programminghunter.com/article/35971402517/">https://www.programminghunter.com/article/35971402517/</a></p>
<h3 id="sftp-go"><a href="#sftp-go" class="headerlink" title="sftp.go"></a>sftp.go</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br></pre></td><td class="code"><pre><span class="line">package sshclient</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">	&quot;fmt&quot;</span><br><span class="line">	&quot;log&quot;</span><br><span class="line">	&quot;net&quot;</span><br><span class="line">	&quot;os&quot;</span><br><span class="line">	&quot;path&quot;</span><br><span class="line">	&quot;time&quot;</span><br><span class="line"></span><br><span class="line">	&quot;github.com/pkg/sftp&quot;</span><br><span class="line">	&quot;golang.org/x/crypto/ssh&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func connect(user, password, host string, port int) (*sftp.Client, error) &#123;</span><br><span class="line">	var (</span><br><span class="line">		auth         []ssh.AuthMethod</span><br><span class="line">		addr         string</span><br><span class="line">		clientConfig *ssh.ClientConfig</span><br><span class="line">		sshClient    *ssh.Client</span><br><span class="line">		sftpClient   *sftp.Client</span><br><span class="line">		err          error</span><br><span class="line">	)</span><br><span class="line">	// get auth method</span><br><span class="line">	auth = make([]ssh.AuthMethod, 0)</span><br><span class="line">	auth = append(auth, ssh.Password(password))</span><br><span class="line">	hostKeyCallbk := func(hostname string, remote net.Addr, key ssh.PublicKey) error &#123;</span><br><span class="line">		return nil</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	clientConfig = &amp;ssh.ClientConfig&#123;</span><br><span class="line">		User:            user,</span><br><span class="line">		Auth:            auth,</span><br><span class="line">		Timeout:         1 * time.Second,</span><br><span class="line">		HostKeyCallback: hostKeyCallbk,</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	// connet to ssh</span><br><span class="line">	addr = fmt.Sprintf(&quot;%s:%d&quot;, host, port)</span><br><span class="line"></span><br><span class="line">	if sshClient, err = ssh.Dial(&quot;tcp&quot;, addr, clientConfig); err != nil &#123;</span><br><span class="line">		return nil, err</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	// create sftp client</span><br><span class="line">	if sftpClient, err = sftp.NewClient(sshClient); err != nil &#123;</span><br><span class="line">		return nil, err</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	return sftpClient, nil</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//发送文件</span><br><span class="line">func SftpPut(user, password, host, fileName string) &#123;</span><br><span class="line">	var (</span><br><span class="line">		err        error</span><br><span class="line">		sftpClient *sftp.Client</span><br><span class="line">	)</span><br><span class="line"></span><br><span class="line">	// 这里换成实际的 SSH 连接的 用户名，密码，主机名或IP，SSH端口</span><br><span class="line">	sftpClient, err = connect(user, password, host, 22)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer sftpClient.Close()</span><br><span class="line"></span><br><span class="line">	// 用来测试的本地文件路径 和 远程机器上的文件夹</span><br><span class="line">	var localFilePath = fileName</span><br><span class="line">	var remoteDir = &quot;/tmp/&quot;</span><br><span class="line">	srcFile, err := os.Open(localFilePath)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer srcFile.Close()</span><br><span class="line"></span><br><span class="line">	var remoteFileName = path.Base(localFilePath)</span><br><span class="line">	dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer dstFile.Close()</span><br><span class="line"></span><br><span class="line">	buf := make([]byte, 1024)</span><br><span class="line">	for &#123;</span><br><span class="line">		n, _ := srcFile.Read(buf)</span><br><span class="line">		if n == 0 &#123;</span><br><span class="line">			break</span><br><span class="line">		&#125;</span><br><span class="line">		dstFile.Write(buf[:n])</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	fmt.Println(&quot;copy file to remote server finished!&quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//下载文件</span><br><span class="line">func SftpGet(user, password, host, fileName string) &#123;</span><br><span class="line"></span><br><span class="line">	var (</span><br><span class="line">		err        error</span><br><span class="line">		sftpClient *sftp.Client</span><br><span class="line">	)</span><br><span class="line"></span><br><span class="line">	// 这里换成实际的 SSH 连接的 用户名，密码，主机名或IP，SSH端口</span><br><span class="line">	sftpClient, err = connect(user, password, host, 22)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer sftpClient.Close()</span><br><span class="line"></span><br><span class="line">	// 用来测试的远程文件路径 和 本地文件夹</span><br><span class="line">	var remoteFilePath = &quot;/tmp/&quot; + fileName</span><br><span class="line">	var localDir = &quot;lib/sshclient/sftpput/&quot;</span><br><span class="line"></span><br><span class="line">	srcFile, err := sftpClient.Open(remoteFilePath)</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer srcFile.Close()</span><br><span class="line"></span><br><span class="line">	var localFileName = path.Base(remoteFilePath)</span><br><span class="line">	dstFile, err := os.Create(path.Join(localDir, localFileName))</span><br><span class="line">	if err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line">	defer dstFile.Close()</span><br><span class="line"></span><br><span class="line">	if _, err = srcFile.WriteTo(dstFile); err != nil &#123;</span><br><span class="line">		log.Fatal(err)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	fmt.Println(&quot;copy file from remote server finished!&quot;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="sshclient-go"><a href="#sshclient-go" class="headerlink" title="sshclient.go"></a>sshclient.go</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> sshclient</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">go 1.14:</span></span><br><span class="line"><span class="comment">mkdir -p $GOPATH/src/golang.org/x/</span></span><br><span class="line"><span class="comment">cd $GOPATH/src/golang.org/x/</span></span><br><span class="line"><span class="comment">git clone https://github.com/golang/crypto.git</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">go 1.18</span></span><br><span class="line"><span class="comment">go get golang.org/x/crypto/ssh</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">&quot;bytes&quot;</span></span><br><span class="line">	<span class="string">&quot;fmt&quot;</span></span><br><span class="line">	<span class="string">&quot;net&quot;</span></span><br><span class="line">	<span class="string">&quot;strings&quot;</span></span><br><span class="line">	<span class="string">&quot;time&quot;</span></span><br><span class="line"></span><br><span class="line">	<span class="string">&quot;golang.org/x/crypto/ssh&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">// SSHConnect ssh连接</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">SSHConnect</span><span class="params">(user, password, host <span class="type">string</span>, port <span class="type">int</span>)</span></span> (*ssh.Client, *ssh.Session, <span class="type">error</span>) &#123;</span><br><span class="line">	<span class="keyword">var</span> (</span><br><span class="line">		auth         []ssh.AuthMethod</span><br><span class="line">		addr         <span class="type">string</span></span><br><span class="line">		clientConfig *ssh.ClientConfig</span><br><span class="line">		client       *ssh.Client</span><br><span class="line">		session      *ssh.Session</span><br><span class="line">		err          <span class="type">error</span></span><br><span class="line">	)</span><br><span class="line">	<span class="comment">// get auth method</span></span><br><span class="line">	auth = <span class="built_in">make</span>([]ssh.AuthMethod, <span class="number">0</span>)</span><br><span class="line">	auth = <span class="built_in">append</span>(auth, ssh.Password(password))</span><br><span class="line"></span><br><span class="line">	hostKeyCallbk := <span class="function"><span class="keyword">func</span><span class="params">(hostname <span class="type">string</span>, remote net.Addr, key ssh.PublicKey)</span></span> <span class="type">error</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	clientConfig = &amp;ssh.ClientConfig&#123;</span><br><span class="line">		User:            user,</span><br><span class="line">		Auth:            auth,</span><br><span class="line">		Timeout:         <span class="number">1</span> * time.Second,</span><br><span class="line">		HostKeyCallback: hostKeyCallbk,</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// connet to ssh</span></span><br><span class="line">	addr = fmt.Sprintf(<span class="string">&quot;%s:%d&quot;</span>, host, port)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span> client, err = ssh.Dial(<span class="string">&quot;tcp&quot;</span>, addr, clientConfig); err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">nil</span>, <span class="literal">nil</span>, err</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// create session</span></span><br><span class="line">	<span class="keyword">if</span> session, err = client.NewSession(); err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> client, <span class="literal">nil</span>, err</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> client, session, <span class="literal">nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// RunSSHpiliang 执行ssh 批量登陆执行</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">RunSSHpiliang</span><span class="params">(user, password, host, cmdshell <span class="type">string</span>)</span></span> <span class="type">string</span> &#123;</span><br><span class="line">	<span class="keyword">var</span> stdOut, stdErr bytes.Buffer</span><br><span class="line">	client, session, err := SSHConnect(user, password, host, <span class="number">22</span>)</span><br><span class="line">	<span class="keyword">if</span> client != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">defer</span> client.Close()</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> session != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">defer</span> session.Close()</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="comment">//fmt.Println(err,&quot;   wei----------------------------------------&quot;)</span></span><br><span class="line">		<span class="keyword">if</span> strings.Contains(err.Error(), <span class="string">&quot;i/o timeout&quot;</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="string">&quot;连接主机的22端口时出错&quot;</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> strings.Contains(err.Error(), <span class="string">&quot;unable to authenticate&quot;</span>) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="string">&quot;密码或SSHKEY验证时出错&quot;</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">&quot;登录主机时出错&quot;</span></span><br><span class="line">	&#125;</span><br><span class="line">	session.Stdout = &amp;stdOut</span><br><span class="line">	session.Stderr = &amp;stdErr</span><br><span class="line">	<span class="keyword">if</span> err := session.Run(cmdshell); err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="comment">// fmt.Println(err.Error())</span></span><br><span class="line">		<span class="comment">// fmt.Println(stdOut.String())</span></span><br><span class="line">		<span class="keyword">return</span> <span class="string">&quot;执行命令时出错！&quot;</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> stdOut.String()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="golang-文件IO-x2F-目录IO-x2F-行IO-x2F-字节BUFIO"><a href="#golang-文件IO-x2F-目录IO-x2F-行IO-x2F-字节BUFIO" class="headerlink" title="golang 文件IO&#x2F;目录IO&#x2F;行IO&#x2F;字节BUFIO"></a>golang 文件IO&#x2F;目录IO&#x2F;行IO&#x2F;字节BUFIO</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">	<span class="string">&quot;bufio&quot;</span></span><br><span class="line">	<span class="string">&quot;fmt&quot;</span></span><br><span class="line">	<span class="string">&quot;io&quot;</span></span><br><span class="line">	<span class="string">&quot;os&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">weiShuoMing</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 删除覆盖   os.OpenFile(&quot;aaa&quot;, os.O_CREATE|os.O_RDWR, 6)</span></span><br><span class="line">	<span class="comment">// 行写文件   os.Openfile(&quot;aaa&quot;, os.O_CREATE|os.O_RDWD|os.O_APPEND,6)   f.WriteString(&quot;&quot;)</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// reader定义 reader,err := bufio.Reader(f)</span></span><br><span class="line">	<span class="comment">// 行读文件   os.Openfile(&quot;aaa&quot;,io.O_RDONLY,6) 或者用 os.Open(&quot;aaa&quot;)  f.ReadBytes(&#x27;\n&#x27;)</span></span><br><span class="line">	<span class="comment">// 偏移量     io.Seek(-12,io.SeekBeging) 还有Current和End</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// buf大小	 buf := make([]byte,4096)</span></span><br><span class="line">	<span class="comment">// 字节写文件  n,err:=reader.write(buf)</span></span><br><span class="line">	<span class="comment">// 字节读文件  n,err:=reader.read(buf)</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// 打开目录    os.Openfile(&quot;aaa&quot;,io.O_RDONLY,os.ModeDir)</span></span><br><span class="line">	<span class="comment">// 读取目录项   f.Readdir(-1) 返回[&#123;Size() Name() IsDir() Modetime()&#125;...]</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">// https://studygolang.com/pkgdoc</span></span><br><span class="line">	<span class="comment">// https://www.bilibili.com/video/BV1TK4y1a7ex?from=search&amp;seid=18159148304738299137</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 创建覆盖文件</span></span><br><span class="line">	os.Create(<span class="string">&quot;aaa&quot;</span>)</span><br><span class="line">	<span class="comment">// 打开文件aaa</span></span><br><span class="line">	f, err := os.OpenFile(<span class="string">&quot;aaa&quot;</span>, os.O_RDWR|os.O_APPEND, <span class="number">6</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &amp;&amp; err != io.EOF &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;OpenFile打开文件aaa出错&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> f.Close()</span><br><span class="line">	<span class="comment">// 写入5行数据</span></span><br><span class="line">	f.WriteString(<span class="string">&quot;写入数据0001\n&quot;</span>)</span><br><span class="line">	f.WriteString(<span class="string">&quot;写入数据0002\n写入数据0003\n&quot;</span>)</span><br><span class="line">	f.WriteString(<span class="string">&quot;写入数据0004\n写入数据0005\n&quot;</span>)</span><br><span class="line">	<span class="comment">// 移至文件开头</span></span><br><span class="line">	f.Seek(<span class="number">0</span>, io.SeekStart)</span><br><span class="line">	<span class="comment">// 读取第2,3行的数据</span></span><br><span class="line">	reader := bufio.NewReader(f)</span><br><span class="line">	i := <span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> &#123;</span><br><span class="line">		hang, err := reader.ReadBytes(<span class="string">&#x27;\n&#x27;</span>)</span><br><span class="line">		<span class="keyword">if</span> err == io.EOF &#123;</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			i++</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> i == <span class="number">2</span> || i == <span class="number">3</span> &#123;</span><br><span class="line">			fmt.Print(<span class="type">string</span>(hang))</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// buf读</span></span><br><span class="line">	<span class="comment">// 偏移15字节再读取第12,13,14,15,16,17,18,19个字节 (utf8一个汉字3个字节,换行\n为一个字节)</span></span><br><span class="line">	f.Seek(<span class="number">15</span>, io.SeekStart)</span><br><span class="line">	buf := <span class="built_in">make</span>([]<span class="type">byte</span>, <span class="number">8</span>)</span><br><span class="line">	f.Read(buf) <span class="comment">//从f中读取一个buf空间的内容，给buf赋值。这个函数还返回n,err其中n是实际读取的切片长度。</span></span><br><span class="line">	fmt.Printf(<span class="string">&quot;%q\n&quot;</span>, buf)</span><br><span class="line">	<span class="comment">// buf写</span></span><br><span class="line">	f.Seek(<span class="number">0</span>, io.SeekEnd)</span><br><span class="line">	f.Write(buf)</span><br><span class="line">	f.Close()</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 读取文件夹</span></span><br><span class="line">	fd, err := os.OpenFile(<span class="string">&quot;D:/w_gopath/src/wei01/w_go_pg_tidb/05.go_wei&quot;</span>, os.O_RDONLY, os.ModeDir)</span><br><span class="line">	<span class="keyword">defer</span> fd.Close()</span><br><span class="line">	fdreader, err := fd.Readdir(<span class="number">-1</span>)</span><br><span class="line">	<span class="keyword">for</span> zixiang, info := <span class="keyword">range</span> fdreader &#123;</span><br><span class="line">		fmt.Println(zixiang, info.Name(), info.Size(), info.ModTime(), info.IsDir())</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 大文件复制</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">weicopy</span><span class="params">()</span></span> &#123;</span><br><span class="line">	f4, err := os.Open(<span class="string">&quot;wei.mp3&quot;</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &amp;&amp; err != io.EOF &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;打开mp3失败&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> f4.Close()</span><br><span class="line"></span><br><span class="line">	f5, err := os.Create(<span class="string">&quot;wei_2.mp3&quot;</span>)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &amp;&amp; err != io.EOF &#123;</span><br><span class="line">		fmt.Println(<span class="string">&quot;打开mp3失败&quot;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">defer</span> f5.Close()</span><br><span class="line"></span><br><span class="line">	buf4k := <span class="built_in">make</span>([]<span class="type">byte</span>, <span class="number">4096</span>)</span><br><span class="line">	<span class="keyword">for</span> &#123;</span><br><span class="line">		n, err := f4.Read(buf4k)</span><br><span class="line">		f5.Write(buf4k[:n])</span><br><span class="line">		<span class="keyword">if</span> err != <span class="literal">nil</span> &amp;&amp; err != io.EOF &#123;</span><br><span class="line">			fmt.Println(<span class="string">&quot;读取文件出错&quot;</span>)</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> n == <span class="number">0</span> &#123;</span><br><span class="line">			fmt.Println(<span class="string">&quot;文件全部读完了&quot;</span>)</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">		&#125;</span><br><span class="line">		fmt.Println(n)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p> JSON（<a target="_blank" rel="noopener" href="http://c.biancheng.net/js/">JavaScript</a> Object Notation）是一种轻量级的数据交换格式，易于阅读和编写，同时也易于机器解析和生成。它基于 <a target="_blank" rel="noopener" href="http://c.biancheng.net/java/">Java</a>Script Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一个子集。</p>
<p> JSON 是一种使用 UTF-8 编码的纯文本格式，采用完全独立于语言的文本格式，由于写起来比 XML 格式方便，并且更为紧凑，同时所需的处理时间也更少，致使 JSON 格式越来越流行，特别是在通过网络连接传送数据方面。</p>
<p> 开发人员可以使用 JSON 传输简单的字符串、数字、布尔值，也可以传输一个数组或者一个更复杂的复合结构。在 Web 开发领域中，JSON 被广泛应用于 Web 服务端程序和客户端之间的数据通信。</p>
<p> Go语言内建对 JSON 的支持，使用内置的 encoding&#x2F;json 标准库，开发人员可以轻松使用Go程序生成和解析 JSON 格式的数据。</p>
<p> JSON 结构如下所示： </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span><span class="attr">&quot;key1&quot;</span><span class="punctuation">:</span><span class="string">&quot;value1&quot;</span><span class="punctuation">,</span><span class="attr">&quot;key2&quot;</span><span class="punctuation">:</span>value2<span class="punctuation">,</span><span class="attr">&quot;key3&quot;</span><span class="punctuation">:</span><span class="punctuation">[</span><span class="string">&quot;value3&quot;</span><span class="punctuation">,</span><span class="string">&quot;value4&quot;</span><span class="punctuation">,</span><span class="string">&quot;value5&quot;</span><span class="punctuation">]</span><span class="punctuation">&#125;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="写-JSON-文件"><a href="#写-JSON-文件" class="headerlink" title="写 JSON 文件"></a>写 JSON 文件</h2><p> 使用Go语言创建一个 json 文件非常方便，示例代码如下： </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;encoding/json&quot;</span></span><br><span class="line">    <span class="string">&quot;fmt&quot;</span></span><br><span class="line">    <span class="string">&quot;os&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Website <span class="keyword">struct</span> &#123;</span><br><span class="line">    Name   <span class="type">string</span> <span class="string">`xml:&quot;name,attr&quot;`</span></span><br><span class="line">    Url    <span class="type">string</span></span><br><span class="line">    Course []<span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    info := []Website&#123;&#123;<span class="string">&quot;Golang&quot;</span>, <span class="string">&quot;http://c.biancheng.net/golang/&quot;</span>, []<span class="type">string</span>&#123;<span class="string">&quot;http://c.biancheng.net/cplus/&quot;</span>, <span class="string">&quot;http://c.biancheng.net/linux_tutorial/&quot;</span>&#125;&#125;, &#123;<span class="string">&quot;Java&quot;</span>, <span class="string">&quot;http://c.biancheng.net/java/&quot;</span>, []<span class="type">string</span>&#123;<span class="string">&quot;http://c.biancheng.net/socket/&quot;</span>, <span class="string">&quot;http://c.biancheng.net/python/&quot;</span>&#125;&#125;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建文件</span></span><br><span class="line">    filePtr, err := os.Create(<span class="string">&quot;info.json&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;文件创建失败&quot;</span>, err.Error())</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">defer</span> filePtr.Close()</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建Json编码器</span></span><br><span class="line">    encoder := json.NewEncoder(filePtr)</span><br><span class="line"></span><br><span class="line">    err = encoder.Encode(info)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;编码错误&quot;</span>, err.Error())</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;编码成功&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p> 运行上面的代码会在当前目录下生成一个 info.json 文件，文件内容如下：  </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">[</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;Name&quot;</span><span class="punctuation">:</span><span class="string">&quot;Golang&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;Url&quot;</span><span class="punctuation">:</span><span class="string">&quot;http://c.biancheng.net/golang/&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;Course&quot;</span><span class="punctuation">:</span><span class="punctuation">[</span></span><br><span class="line">            <span class="string">&quot;http://c.biancheng.net/golang/102/&quot;</span><span class="punctuation">,</span></span><br><span class="line">            <span class="string">&quot;http://c.biancheng.net/golang/concurrent/&quot;</span></span><br><span class="line">        <span class="punctuation">]</span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;Name&quot;</span><span class="punctuation">:</span><span class="string">&quot;Java&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;Url&quot;</span><span class="punctuation">:</span><span class="string">&quot;http://c.biancheng.net/java/&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;Course&quot;</span><span class="punctuation">:</span><span class="punctuation">[</span></span><br><span class="line">            <span class="string">&quot;http://c.biancheng.net/java/10/&quot;</span><span class="punctuation">,</span></span><br><span class="line">            <span class="string">&quot;http://c.biancheng.net/python/&quot;</span></span><br><span class="line">        <span class="punctuation">]</span></span><br><span class="line">    <span class="punctuation">&#125;</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure>

<h2 id="读-JSON-文件"><a href="#读-JSON-文件" class="headerlink" title="读 JSON 文件"></a>读 JSON 文件</h2><p> 读 JSON 数据与写 JSON 数据一样简单，示例代码如下： </p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;encoding/json&quot;</span></span><br><span class="line">    <span class="string">&quot;fmt&quot;</span></span><br><span class="line">    <span class="string">&quot;os&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Website <span class="keyword">struct</span> &#123;</span><br><span class="line">    Name   <span class="type">string</span> <span class="string">`xml:&quot;name,attr&quot;`</span></span><br><span class="line">    Url    <span class="type">string</span></span><br><span class="line">    Course []<span class="type">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    filePtr, err := os.Open(<span class="string">&quot;./info.json&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;文件打开失败 [Err:%s]&quot;</span>, err.Error())</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">defer</span> filePtr.Close()</span><br><span class="line">    <span class="keyword">var</span> info []Website</span><br><span class="line">    <span class="comment">// 创建json解码器</span></span><br><span class="line">    decoder := json.NewDecoder(filePtr)</span><br><span class="line">    err = decoder.Decode(&amp;info)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;解码失败&quot;</span>, err.Error())</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        fmt.Println(<span class="string">&quot;解码成功&quot;</span>)</span><br><span class="line">        fmt.Println(info)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p> 运行结果如下： </p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">go run main.go</span><br><span class="line">解码成功</span><br><span class="line"><span class="punctuation">[</span><span class="punctuation">&#123;</span>Golang http<span class="punctuation">:</span><span class="comment">//c.biancheng.net/golang/ [http://c.biancheng.net/golang/102/ http://c.biancheng.net/golang/concurrent/]&#125; &#123;Java http://c.biancheng.net/java/ [http://c.biancheng.net/java/10/ http://c.biancheng.net/python/]&#125;]</span></span><br></pre></td></tr></table></figure>

<p>顺便提一下，还有一种叫做 BSON (Binary JSON) 的格式与 JSON 非常类似，与 JSON 相比，BSON 着眼于提高存储和扫描效率。BSON  文档中的大型元素以长度字段为前缀以便于扫描。在某些情况下，由于长度前缀和显式数组索引的存在，BSON 使用的空间会多于 JSON。</p>
<h1 id="Golang-操作mysql"><a href="#Golang-操作mysql" class="headerlink" title="Golang 操作mysql"></a>Golang 操作mysql</h1><figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">go get github.com/go<span class="literal">-sql-driver</span>/mysql</span><br><span class="line">go get github.com/jmoiron/sqlx</span><br></pre></td></tr></table></figure> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://example.com/2023/05/10/%E5%85%A5%E9%97%A8-Golang%E4%B9%8B%E8%B7%AF/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%9F%BA%E7%A1%80/" rel="tag">基础</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2023/05/10/%E5%85%A5%E9%97%A8-JAVA%E4%B9%8B%E8%B7%AF/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            入门-JAVA之路
          
        </div>
      </a>
    
    
      <a href="/2023/05/10/%E5%85%A5%E9%97%A8-Vue%E4%B9%8B%E8%B7%AF/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">入门-Vue之路</div>
      </a>
    
  </nav>

  
   
  
    
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2023-2024
        <i class="ri-heart-fill heart_icon"></i> Wang Wei
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ww.ico" alt="朝花夕拾"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.staticfile.org/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.staticfile.org/clipboard.js/2.0.10/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->

<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>